import {
  Card,
  Breadcrumb,
  Form,
  Select,
  Button,
  Input,
  Space,
  Radio,
  Upload,
  message,
} from "antd"
import { Link, useHistory, useParams } from "react-router-dom"
import { useDispatch, useSelector } from "react-redux"
import {
  getChannels,
  addArticle,
  getArticleInfo,
  editArticle,
} from "@/store/actions/article"
import { useEffect, useState, useMemo } from "react"
import { PlusOutlined } from "@ant-design/icons"
import styles from "./index.module.scss"
import ReactQuill from "react-quill"
import "react-quill/dist/quill.snow.css"
const Publish = () => {
  const [form] = Form.useForm()
  const params = useParams()
  const history = useHistory()
  const [type, setType] = useState(1) // 设置初始图片类型
  const [fileList, setFileList] = useState([])
  const showText = useMemo(() => {
    return params.id ? "修改文章" : "发布文章"
  }, [params])
  const dispatch = useDispatch()
  const channels = useSelector((state) => state.article.channels)
  useEffect(() => {
    dispatch(getChannels())
  }, [dispatch])

  useEffect(() => {
    const getInfo = async () => {
      const { title, content, channel_id, cover } = await dispatch(
        getArticleInfo(params.id)
      )
      // result就是详情
      // 回显 可以使用form对象进行数据的回显设置
      form.setFieldsValue({
        title,
        content,
        channel_id,
      })
      // 设置封面类型
      setType(cover.type)
      // 图片
      // upload能显示图片是因为 [{ url: '图片地址' }]
      // cover = { type:3 , images: ["地址1"， "地址2"， “地址3”] }
      setFileList(cover.images.map((item) => ({ url: item })))
    }
    // 两种场景
    if (params.id) {
      // 编辑
      getInfo()
    } else {
      // 将所有的数据清空
      form.resetFields() // 重置字段
      setType(1) // 重置类型
      setFileList([]) // 重置封面图片
    }
  }, [params, dispatch, form])

  const onTypeChange = (e) => {
    setType(e.target.value)
    setFileList([]) // 切换类型 图片就清空
    // console.log(e.target.value)
  }
  const onUploadChange = ({ fileList }) => {
    console.log(fileList)
    setFileList(fileList) // 将上传成功的数据设置到状态中
  }
  const onFinish = async (values, draft = false) => {
    // 只要校验通过 就会进入这里
    // 此时要判断 当前的图片上传的地址和 类型匹配与否
    if (type !== fileList.length) {
      return message.warning("上传图片与与封面类型不匹配")
    }
    // 提交表单内容到action
    const data = {
      ...values,
      cover: {
        type,
        images: fileList.map((item) => item?.response?.data?.url ?? item.url),
      },
    }
    if (params.id) {
      // 此时认为修改
      await dispatch(editArticle({ id: params.id, ...data }, draft)) // 调用修改接口
    } else {
      await dispatch(addArticle(data, draft))
    }

    message.success("发布成功")
    history.push("/article")
  }

  const saveDraft = async () => {
    // 要完成表单校验
    await form.validateFields()
    // 调用onFinish
    onFinish(form.getFieldsValue(), true) // 表示存的是草稿
  }
  return (
    <div className={styles.root}>
      <Card
        title={
          <Breadcrumb>
            <Breadcrumb.Item>
              <Link to="/">首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>
              <Link to="/article">内容管理</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>{showText}</Breadcrumb.Item>
          </Breadcrumb>
        }
      >
        <Form form={form} labelCol={{ span: 4 }} onFinish={onFinish}>
          <Form.Item
            label="标题"
            name="title"
            rules={[
              {
                required: true,
                message: "标题内容不能为空",
              },
            ]}
          >
            <Input style={{ width: 400 }}></Input>
          </Form.Item>
          <Form.Item
            label="频道"
            name="channel_id"
            rules={[
              {
                required: true,
                message: "频道内容不能为空",
              },
            ]}
          >
            <Select style={{ width: 400 }}>
              {channels.map((item) => (
                <Select.Option key={item.id} value={item.id}>
                  {item.name}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item label="封面" name="cover">
            <Radio.Group value={type} onChange={onTypeChange}>
              <Radio value={1}>单图</Radio>
              <Radio value={3}>三图</Radio>
              <Radio value={0}>无图</Radio>
            </Radio.Group>
            {/* 控制upload组件的显示和隐藏 */}
            {type > 0 ? (
              <div style={{ marginTop: 16 }}>
                <Upload
                  name="image"
                  listType="picture-card"
                  action="http://toutiao.itheima.net/v1_0/upload"
                  fileList={fileList} // 要展示的文件列表
                  onPreview={() => {}}
                  onChange={onUploadChange}
                >
                  {/* 意思是只有 当 未传图片的张数未满足总张数的时候 才显示上传 */}
                  {fileList.length < type ? (
                    <div>
                      <PlusOutlined />
                      <div style={{ marginTop: 8 }}>Upload</div>
                    </div>
                  ) : null}
                </Upload>
              </div>
            ) : null}
          </Form.Item>
          <Form.Item
            wrapperCol={{ span: 16 }}
            label="内容"
            name="content"
            initialValue=""
            rules={[
              {
                required: true,
                message: "文章内容不能为空",
              },
            ]}
          >
            <ReactQuill></ReactQuill>
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 4 }}>
            <Space>
              <Button size="large" type="primary" htmlType="submit">
                {showText}
              </Button>
              <Button size="large" onClick={saveDraft}>
                存入草稿
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>
    </div>
  )
}
export default Publish
